
#ifndef _MEMBER_BGEOMETRY_H_
#define _MEMBER_BGEOMETRY_H_

#include <BTriangle>
#include <BQuad>
#include <BPolygon>
#include <BProgram>
#include <BTexture>
#include <BMaterial>
#include <BVectorArray>
#include <BCoordArray>
#include <BColorArray>
#include <BGeometry>
#include <BElement>
#include <BOctTree>
#include "ITriangleCallback.h"

#define geometry_member(geometry)		((member_BGeometry*)((BGeometry*)geometry)->_ptr)

namespace BWE
{
	typedef BArray<BTriangle>	BTriangleArray;
	typedef BArray<BQuad>		BQuadArray;
	typedef BArray<BPolygon>	BPolygonArray;

	struct PolyCell : public BThing
	{
		PolyCell()
		{
			element = 0;
		}

		BTriangleArray		triangles;
		BQuadArray			quads;
		BPolygonArray		polygons;
		BElement*			element;
	};

	typedef BOctTree<PolyCell>				PolyOctTree;
	typedef BOctTree<PolyCell>::Item		PolyOctTreeItem;
	typedef BOctTree<PolyCell>::ItemArray	PolyOctTreeItemArray;

	class member_BGeometry
	{
		friend class BGeometry;

		struct Node
		{
			BSpace	space;
			BVector	center;
			int		index = -1;
			int		ia = -1;
			int		ib = -1;
			int		ic = -1;
			int		id = -1;
		};

	public:
		member_BGeometry(BGeometry* geometry);
		~member_BGeometry();

		void drawPiecesLObject(BElement* element, int mode);

		BSpace triangleSpace(const BTriangle& triangle) const;
		BSpace quadSpace(const BQuad& quad) const;
		BSpace polygonSpace(const BPolygon& polygon) const;

		void freshPolyTree();
		void freshElementBoxes();

		void buildTree(int startIndex, int endIndex);
		void overlapping(ITriangleCallback* callback, const BSpace& space);
		void overlapping(ITriangleCallback* callback, const BLine& line);
		void processNode(ITriangleCallback* callback, const Node& node);

		BGeometry*					boss;
		BHolder<BVectorArray>		vertices;
		BHolder<BVectorArray>		normals;
		BHolder<BColorArray>		colors;
		BArray<BCoordArrayHolder>	coords;
		BArray<BElementHolder>		elements;
		BHolder<PolyOctTree>		polyOctTree;

		bool					dirtyTree;
		BSpace					localSpace;
		int						lastIndex;
		BArray<Node>			leafNodes;
		BArray<Node>			treeNodes;

	};
}

#endif